﻿//Created by Action Script Viewer - http://www.buraks.com/asv
package {
    import Engine.Classes.*;
    import flash.events.*;
    import Engine.Events.*;
    import Engine.Transactions.*;
    import Engine.Managers.*;
    import flash.display.*;
    import Engine.Init.*;
    import Mechanics.GameMechanicInterfaces.*;
    import Mechanics.*;
    import flash.utils.*;
    import Display.DialogUI.*;
    import org.aswing.*;
    import Classes.*;
    import Transactions.*;
    import Classes.util.*;
    import Classes.sim.*;
    import __AS3__.vec.*;
    import com.zynga.skelly.render.*;
    import plugin.*;
    import Modules.bandits.*;
    import tool.*;
    import Modules.quest.Managers.*;
    import Display.*;
    import Classes.virals.*;
    import Display.CopsBanditsUI.*;
    import GameMode.*;
    import Display.Toaster.*;
    import Modules.realtime.*;
    import Modules.guide.*;
    import Modules.stats.experiments.*;
    import Modules.zoo.ui.*;
    import Init.*;
    import Classes.Managers.*;
    import flash.system.*;
    import Engine.*;
    import Modules.crew.ui.*;
    import Classes.zbar.*;
    import blit.*;
    import Classes.MiniQuest.*;
    import com.greensock.plugins.*;
    import Mechanics.GameEventMechanics.*;
    import Modules.stats.trackers.*;
    import Modules.stats.types.*;
    import L10n.*;
    import Display.FriendRewardsUI.*;
    import Modules.zoo.*;
    import flash.external.*;

    public class Game extends BaseGame {

        public static const DEBUG_PRODUCTION_OVERRIDE:Boolean = false;

        public static var m_blitting:Boolean = false;

        private const FRAME_RATE:int = 30;

        protected var m_initializing:Boolean;
        protected var m_feedOpenTime:Number;
        protected var m_warningDialog:GenericDialog;
        private var debug_defcon:int = 0;
        private var m_zmcFreeze:Boolean = false;
        private var m_zmcFreezeCount:int = 0;
        private var m_zmcOpen:Boolean = false;
        private var m_pendingTransactionData:Dictionary;
        private var m_completedTransactionData:Vector.<TransactionTrackingData>;
        private var m_pendingBatchData:Vector.<BatchTrackingData>;
        private var m_completedBatchData:Vector.<BatchTrackingData>;

        public function Game(_arg1:Object=null){
            this.m_pendingTransactionData = new Dictionary();
            this.m_completedTransactionData = new Vector.<TransactionTrackingData>();
            this.m_pendingBatchData = new Vector.<BatchTrackingData>();
            this.m_completedBatchData = new Vector.<BatchTrackingData>();
            LoadingManager.maxLoadsPerDomain = 6;
            LoadingManager.maxLoads = 24;
            var _local2:ZEngineOptions = new ZEngineOptions();
            if (m_blitting){
                _local2.viewportClass = BlitViewport;
            } else {
                _local2.viewportClass = IsoViewport;
            };
            _local2.zaspManagerClass = GameZaspManager;
            _local2.tileWidth = 10;
            _local2.tileHeight = 5;
            var _local3:QuestComponentOptions = new QuestComponentOptions();
            _local3.questClass = GameQuest;
            _local3.questUtility = GameQuestUtility;
            _local2.addComponent(new QuestComponent(_local3));
            super(_arg1, _local2);
        }
        override protected function init():void{
            if (parameters.localization_url){
                LocaleHelper.locale = LocaleHelper.getLangByURL(parameters.localization_url);
            };
            StartupSessionTracker.track(StatsPhylumType.STARTUP_GAME_INIT);
            StartupSessionTracker.perf(StatsKingdomType.LOADAPP);
            if (Global.isSandbox){
                Config.verboseLogging = true;
                GlobalEngine.addTraceLevel("StateMachine", GlobalEngine.LEVEL_WARNING);
                GlobalEngine.addTraceLevel("QuestManager", GlobalEngine.LEVEL_ALL);
                GlobalEngine.addTraceLevel("Guide", GlobalEngine.LEVEL_ALL);
                GlobalEngine.addTraceLevel("Doobers", GlobalEngine.LEVEL_ALL);
                GlobalEngine.addTraceLevel("AMFConnection", GlobalEngine.LEVEL_ALL);
            };
            GlobalEngine.addTraceLevel("Init", GlobalEngine.LEVEL_ALL);
            Global.stage = this.stage;
            TweenPlugin.activate([GlowFilterPlugin]);
            if (m_blitting){
                Global.stage.quality = StageQuality.LOW;
            };
            RenderManager.init((GlobalEngine.viewport as IRenderer), stage, this.FRAME_RATE, false);
            UIManager.setLookAndFeel((LocaleHelper.localSetting.generateObject(CityASwingSkin) as CityASwingSkin));
            GlobalEngine.stage.stageFocusRect = false;
            RepaintManager.getInstance().setAlwaysUseTimer(true, this.FRAME_RATE);
            AsWingManager.setPreventNullFocus(false);
            var _local1 = (Config.BASE_PATH + "bootstrap.xml");
            var _local2 = (Config.BASE_PATH + "gameSettings.xml");
            var _local3 = (Config.BASE_PATH + "en_US.xml");
            var _local4 = (Config.BASE_PATH + "questSettings.xml");
            var _local5 = (Config.BASE_PATH + "effectsConfig.xml");
            if (parameters.bootstrap_url){
                _local1 = parameters.bootstrap_url;
            };
            if (parameters.game_config_url){
                _local2 = parameters.game_config_url;
            };
            if (parameters.localization_url){
                _local3 = parameters.localization_url;
            };
            if (parameters.quest_config_url){
                _local4 = parameters.quest_config_url;
            };
            if (parameters.effects_config_url){
                _local5 = parameters.effects_config_url;
            };
            if (parameters.visitId){
                Global.setVisiting(parameters.visitId);
            };
            GlobalEngine.log("Init", ("Game Config URL: " + _local2));
            this.m_initializing = true;
            TransactionManager.getInstance().addEventListener(TransactionFaultEvent.FAULT, this.onInitTransactionFault);
            var _local6 = (parameters.skipFacebook == true);
            var _local7:InitializationManager = GlobalEngine.initializationManager;
            _local7.add(new ExperimentsInit());
            _local7.add(new BootstrapInit(_local1));
            _local7.add(new RuntimeVariableInit());
            _local7.add(new ServiceInit());
            _local7.add(new LoadingInit());
            _local7.add(new GameSettingsInit(_local2));
            _local7.add(new LocalizationInit(_local3));
            _local7.add(new LocaleFontInit());
            if (((!((GlobalEngine.getFlashVar("snapiEnable") == null))) && ((parseInt(GlobalEngine.getFlashVar("snapiEnable").toString()) == 1)))){
                _local7.add(new SNAPIInit(_local6));
            } else {
                _local7.add(new GameFacebookInit(_local6));
            };
            _local7.add(new TransactionsInit());
            _local7.add(new GlobalsInit());
            _local7.add(new UIInit());
            _local7.add(new AssetLoadingInit());
            _local7.add(new FontMapperInit());
            _local7.add(new GuideInit());
            _local7.add(new EffectsInit(_local5));
            _local7.add(new StatsInit(_local7));
            _local7.add(new ItemImageBundleInit());
            if (Config.DEBUG_MODE){
                _local7.add(new ConsoleInit());
            };
            _local7.addEventListener(ProgressEvent.PROGRESS, this.onInitProgress);
            _local7.addEventListener(Event.COMPLETE, this.onAllInitComplete);
            _local7.execute();
            if (Config.DEBUG_MODE){
                ErrorManager.getInstance().addEventListener(ErrorEvent.ERROR, this.onError);
            };
        }
        private function onInitProgress(_arg1:ProgressEvent):void{
            dispatchEvent(_arg1);
        }
        private function onAllInitComplete(_arg1:Event):void{
            var fps:* = null;
            var ev:* = _arg1;
            GlobalEngine.log("Init", (("onAllInitComplete pre alloc = " + Number(((System.totalMemory / 0x0400) / 0x0400)).toFixed(1)) + "mb"));
            var flash_info:* = GameUtil.logMachineInfo();
            StatsManager.count("Flash_Info", flash_info[0], flash_info[1], flash_info[2], flash_info[3], flash_info[4]);
            this.m_initializing = false;
            if (Config.DEBUG_MODE){
                Config.verboseLogging = true;
                GlobalEngine.addTraceLevel("StateMachine", GlobalEngine.LEVEL_WARNING);
                GlobalEngine.addTraceLevel("QuestManager", GlobalEngine.LEVEL_ALL);
                GlobalEngine.addTraceLevel("Guide", GlobalEngine.LEVEL_ALL);
                GlobalEngine.addTraceLevel("Doobers", GlobalEngine.LEVEL_ALL);
                GlobalEngine.addTraceLevel("AMFConnection", GlobalEngine.LEVEL_ALL);
            };
            TransactionManager.getInstance().removeEventListener(TransactionFaultEvent.FAULT, this.onInitTransactionFault);
            ZyParamsUpdateTracker.initialize();
            if (!m_blitting){
                GlobalEngine.stage.addEventListener(Event.ENTER_FRAME, this.onEnterFrame);
            };
            GlobalEngine.stage.addEventListener(Event.MOUSE_LEAVE, this.onMouseLeaveFrame);
            GlobalEngine.stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullScreenChanged);
            GlobalEngine.viewport.setZoom(Global.gameSettings.getNumber("defaultZoom"));
            GlobalEngine.viewport.width = this.stage.stageWidth;
            GlobalEngine.viewport.height = this.stage.stageHeight;
            addChild(GlobalEngine.viewport);
            GlobalEngine.viewport.scaleX = (GlobalEngine.viewport.scaleY = 1);
            Global.world.centerCityView(0);
            addChild(Global.ui);
            if (m_blitting){
                fps = new FrameRateGraph();
                fps.y = 190;
                fps.x = 20;
                addChild(fps);
                fps.activate();
            };
            var dailyBonusVariant:* = Global.experimentManager.getVariant(ExperimentDefinitions.EXPERIMENT_DAILY_BONUS_AUTOPOP);
            if (dailyBonusVariant == ExperimentDefinitions.DAILY_BONUS_AUTOPOP_ON){
                if (((((Global.questManager.isFlagReached(GameQuestManager.QUEST_UX_VISITS_UNLOCKED)) && (Global.player.dailyBonusManager.isBonusAvailable))) && (!(Global.player.isNewPlayer)))){
                    DailyBonusMQ.doDailyBonus();
                };
            };
            UI.pumpPopupQueue();
            Sounds.unpauseMusic();
            Global.world.resetGenericAdTime();
            GlobalEngine.stage.addEventListener(MouseEvent.MOUSE_MOVE, this.onStageMouseMove, false, 3);
            GlobalEngine.stage.addEventListener(MouseEvent.CLICK, this.onStageMouseClick, false, 3);
            GlobalEngine.stage.addEventListener(KeyboardEvent.KEY_DOWN, this.onStageKeyDown, false, 3);
            dispatchEvent(new Event(Event.COMPLETE));
            TransactionManager.getInstance().addEventListener(TransactionFaultEvent.FAULT, this.onTransactionFault);
            TransactionManager.getInstance().addEventListener(TransactionEvent.QUEUE_LIMIT_EXCEEDED, this.onTransactionQueueLimitExceeded);
            TransactionManager.getInstance().addEventListener(TransactionEvent.QUEUE_LIMIT_NORMAL, this.onTransactionQueueLimitNormal);
            TransactionManager.getInstance().addEventListener(TransactionEvent.VERSION_MISMATCH, this.onTransactionVersionMismatch);
            TransactionManager.getInstance().addEventListener(TransactionEvent.RETRY_SUCCESS, this.onTransactionRetrySuccess);
            TransactionManager.getInstance().addEventListener(TransactionFaultEvent.RETRY, this.onTransactionRetry);
            TransactionManager.getInstance().addEventListener(TransactionEvent.ADDED, this.onTransactionAdded);
            TransactionManager.getInstance().addEventListener(TransactionEvent.DISPATCHED, this.onTransactionDispatched);
            TransactionManager.getInstance().addEventListener(TransactionEvent.COMPLETED, this.onTransactionCompleted);
            TransactionManager.getInstance().addEventListener(TransactionBatchEvent.BATCH_DISPATCHED, this.onTransactionBatchDispatched);
            TransactionManager.getInstance().addEventListener(TransactionBatchEvent.BATCH_COMPLETE, this.onTransactionBatchCompleted);
            if (((parameters.missionType) && (parameters.missionHostId))){
                GameTransactionManager.addTransaction(new TGetVisitMission(parameters.missionHostId, parameters.missionType), true);
            };
            try {
                if (ExternalInterface.available){
                    ExternalInterface.addCallback("enableAllInput", this.enableAllInput);
                    ExternalInterface.addCallback("disableAllInput", this.disableAllInput);
                    ExternalInterface.addCallback("logShowFeedDialog", this.logShowFeedDialog);
                    ExternalInterface.addCallback("logCloseFeedDialog", this.logCloseFeedDialog);
                    ExternalInterface.addCallback("permissionDialogClosed", this.permissionDialogClosed);
                    ExternalInterface.addCallback("onFocus", this.onFocus);
                    ExternalInterface.addCallback("frameLoadComplete", FrameManager.frameLoadComplete);
                    ExternalInterface.addCallback("onDynamicTrayClosed", this.onDynamicTrayClosed);
                    ExternalInterface.addCallback("freezeGame", this.freezeGame);
                    ExternalInterface.addCallback("ZMCFreezeGame", this.ZMCFreezeGame);
                    ExternalInterface.addCallback("thawGame", this.thawGame);
                    ExternalInterface.addCallback("onZMCEvent", this.onZMCEvent);
                    ExternalInterface.addCallback("onZMCOpen", this.onZMCOpen);
                    ExternalInterface.addCallback("onZMCClose", this.onZMCClose);
                    ExternalInterface.addCallback("setZBarQueue", this.setZBarQueue);
                    ExternalInterface.addCallback("onZMCLoad", this.onZMCLoad);
                    ExternalInterface.addCallback("onRTStatusChange", RealtimeManager.onRTStatusChange);
                    ExternalInterface.addCallback("onRTChat", RealtimeManager.onRTChat);
                } else {
                    StatsManager.count("errors", "external_interface_not_supported");
                };
            } catch(error:Error) {
                StatsManager.count("errors", "external_interface_threw_error");
            };
            if (Global.player.isNewPlayer){
                Global.guide.loadLaterStepAssets();
            };
            Global.delayedAssets.startPostloading();
            if (!(((Global.player.options["sfxDisabled"] == true)) && (Global.experimentManager.inPerfExperiment(ExperimentDefinitions.EXPERIMENT_OPTIMIZE_LOADTIME, ExperimentDefinitions.EXPERIMENT_OPTIMIZE_SFX_LOADING)))){
                Sounds.startPostloading();
            };
            Global.world.citySim.waterManager.init();
            FrameManager.doInitPreloads();
            Global.achievementsManager.startFullUpdate();
            if (Global.ui){
                UI.populateFriendBarData([]);
                Global.ui.m_friendBar.preload = true;
                Global.ui.m_friendBar.populateNeighbors(Global.friendbar);
                Global.ui.setFriendBarPos(0);
                Global.ui.m_friendBar.preload = false;
            };
            GameTransactionManager.addTransaction(new TInitNeighbors());
            GameTransactionManager.addTransaction(new TCheckForNewNeighbors());
            GlobalEngine.log("Init", (("onAllInitComplete finished in " + (getTimer() / 1000)) + " s"));
            GlobalEngine.log("Init", (("onAllInitComplete post alloc = " + Number(((System.totalMemory / 0x0400) / 0x0400)).toFixed(1)) + "mb"));
            StartupSessionTracker.track(StatsPhylumType.STARTUP_GAME_INIT_COMPLETE);
            StartupSessionTracker.perf(StatsKingdomType.INITCOMPLETE);
            var zmc_popup_early_variant:* = Global.experimentManager.getVariant(ExperimentDefinitions.EXPERIMENT_POPUP_ZMC_EARLY);
            if (zmc_popup_early_variant == ExperimentDefinitions.POPUP_ZMC_AT_EARLY_STAGE){
                StartupSessionTracker.interactive();
            };
            Global.world.startPerformanceTracking();
            var variant:* = Global.experimentManager.getVariant(ExperimentDefinitions.EXPERIMENT_INCREASE_NUM_OF_QUEUED_TRANSACTIONS);
            if (variant){
                StatsManager.count("transaction_max_queued_increased");
                TransactionManager.maxQueued = (TransactionManager.DEFAULT_MAX_QUEUED * 2);
            };
            RealtimeManager.m_realtimeObserver = new RealtimeObserver();
        }
        private function onInitTransactionFault(_arg1:TransactionFaultEvent):void{
            var _local2:String = _arg1.errorType.toString();
            var _local3:String = (_arg1.errorData) ? _arg1.errorData.toString() : "";
            var _local4:String = ((("Error #" + _local2) + ": ") + _local3);
            dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, _local4));
            this.logErrorStats(_arg1, true);
        }
        private function onTransactionFault(_arg1:TransactionFaultEvent):void{
            if (Config.DEBUG_MODE){
                UI.displayMessage(("errorData: " + _arg1.errorData), GenericPopup.TYPE_OK, GameUtil.redirectHome, "", true);
                this.logErrorStats(_arg1);
            } else {
                if (_arg1.errorType == Transaction.OUTDATED_GAME_VERSION){
                    this.onTransactionVersionMismatch();
                } else {
                    this.onTransactionGeneralError(_arg1);
                };
            };
        }
        private function onTransactionRetry(_arg1:TransactionFaultEvent):void{
            var _local2:int = (Global.gameSettings.getInt("gameConnectionMaxTimeout", 30) * 1000);
            ConnectionStatus.startTimeout(ConnectionStatus.TIMEOUT_CONNECTION_LOST, _local2, true, this.onConnectionTimeout);
        }
        private function onTransactionAdded(_arg1:TransactionEvent):void{
            this.m_pendingTransactionData[_arg1.transaction.getId()] = new TransactionTrackingData(_arg1.transaction);
        }
        private function onTransactionDispatched(_arg1:TransactionEvent):void{
            var _local2:TransactionTrackingData = this.m_pendingTransactionData[_arg1.transaction.getId()];
            if (_local2 != null){
                _local2.dispatchTime = GlobalEngine.currentTime;
            };
        }
        private function onTransactionCompleted(_arg1:TransactionEvent):void{
            var _local2:TransactionTrackingData = this.m_pendingTransactionData[_arg1.transaction.getId()];
            if (_local2 != null){
                _local2.responseTime = GlobalEngine.currentTime;
                _local2.serverDuration = this.fixupSeverTime(_local2.transaction.rawResult["transactionTimeElapsed"]);
                while (this.m_completedTransactionData.length >= TransactionTrackingData.MAX_TRACKED) {
                    this.m_completedTransactionData.shift();
                };
                this.m_completedTransactionData.push(_local2);
                delete this.m_pendingTransactionData[_arg1.transaction.getId()];
            };
        }
        private function onTransactionBatchDispatched(_arg1:TransactionBatchEvent):void{
            var _local2:BatchTrackingData = new BatchTrackingData();
            _local2.dispatchTime = GlobalEngine.currentTime;
            _local2.numTransactions = _arg1.dispatchedBatchData.length;
            this.m_pendingBatchData.unshift(_local2);
        }
        private function onTransactionBatchCompleted(_arg1:TransactionBatchEvent):void{
            var _local2:BatchTrackingData;
            var _local3:Array;
            var _local4:Object;
            if (this.m_pendingBatchData.length > 0){
                _local2 = this.m_pendingBatchData.shift();
                _local2.responseTime = GlobalEngine.currentTime;
                _local2.batchServerTimeElapsed = 0;
                if (((((_arg1.responseBatchData) && (_arg1.responseBatchData.hasOwnProperty("data")))) && ((_arg1.responseBatchData["data"] is Array)))){
                    _local3 = _arg1.responseBatchData["data"];
                    for each (_local4 in _local3) {
                        if (_local4.hasOwnProperty("transactionTimeElapsed")){
                            _local2.batchServerTimeElapsed = (_local2.batchServerTimeElapsed + this.fixupSeverTime(_local4["transactionTimeElapsed"]));
                        };
                    };
                };
                while (this.m_completedBatchData.length >= BatchTrackingData.MAX_TRACKED) {
                    this.m_completedBatchData.shift();
                };
                this.m_completedBatchData.push(_local2);
            };
        }
        private function fixupSeverTime(_arg1:Number):Number{
            return (((_arg1 * 1000) * 1000));
        }
        private function logTransactionData(_arg1:String):void{
            var _local5:TransactionTrackingData;
            var _local6:TransactionTrackingData;
            var _local7:BatchTrackingData;
            var _local8:BatchTrackingData;
            var _local9:String;
            var _local10:String;
            var _local11:String;
            var _local12:String;
            var _local13:String;
            var _local2:String = ("transaction_" + _arg1);
            var _local3:String = ("batch_" + _arg1);
            var _local4 = (Global.experimentManager.getVariant(ExperimentDefinitions.EXPERIMENT_TRACK_TRANSACTION_MAX_QUEUE) == ExperimentDefinitions.TRACK_TRANSACTION_MAX_QUEUE_ENABLED);
            if (_local4){
                for each (_local5 in this.m_pendingTransactionData) {
                    _local9 = getQualifiedClassName(_local5.transaction);
                    _local10 = _local5.addTime.toString();
                    _local11 = (_local5.isDispatched) ? _local5.dispatchTime.toString() : "--";
                    _local12 = "--";
                    _local13 = "--";
                    StatsManager.count(_local2, _local9, _local10, _local11, _local12, _local13);
                };
                for each (_local6 in this.m_completedTransactionData) {
                    _local9 = getQualifiedClassName(_local6.transaction);
                    _local10 = _local6.addTime.toString();
                    _local11 = _local6.dispatchTime.toString();
                    _local12 = _local6.responseTime.toString();
                    _local13 = _local6.serverDuration.toString();
                    StatsManager.count(_local2, _local9, _local10, _local11, _local12, _local13);
                };
                for each (_local7 in this.m_pendingBatchData) {
                    StatsManager.count(_local3, _local7.numTransactions.toString(), _local7.dispatchTime.toString(), "--", "--");
                };
                for each (_local8 in this.m_completedBatchData) {
                    StatsManager.count(_local3, _local8.numTransactions.toString(), _local8.dispatchTime.toString(), _local8.responseTime.toString(), _local8.batchServerTimeElapsed.toString());
                };
            };
            this.m_completedTransactionData = new Vector.<TransactionTrackingData>();
            this.m_completedBatchData = new Vector.<BatchTrackingData>();
        }
        private function onTransactionRetrySuccess(_arg1:TransactionEvent):void{
            ConnectionStatus.stopTimeout();
        }
        private function onTransactionVersionMismatch(_arg1:TransactionEvent=null):void{
            UI.displayMessage(ZLoc.t("Main", "OutdatedGameVersion"), GenericPopup.TYPE_OK, GameUtil.redirectHomeVersionMismatch, "", true);
        }
        private function onTransactionGeneralError(_arg1:TransactionFaultEvent):void{
            UI.displayMessage(ZLoc.t("Main", "RefreshGame"), GenericPopup.TYPE_OK, GameUtil.redirectHome, "", true);
            this.logErrorStats(_arg1);
        }
        private function onTransactionQueueLimitExceeded(_arg1:TransactionEvent):void{
            var _local2:int = (Global.gameSettings.getInt("gameSaveMaxTimeout", 25) * 1000);
            ConnectionStatus.startTimeout(ConnectionStatus.TIMEOUT_SAVE_GAME, _local2, true, this.onConnectionTimeout);
        }
        private function onTransactionQueueLimitNormal(_arg1:TransactionEvent):void{
            this.logTransactionData("queue_recover");
            ConnectionStatus.stopTimeout();
        }
        private function onConnectionTimeout(_arg1:String):void{
            var _local2 = "unknown";
            switch (_arg1){
                case ConnectionStatus.TIMEOUT_SAVE_GAME:
                    _local2 = "queue_backup";
                    break;
                case ConnectionStatus.TIMEOUT_CONNECTION_LOST:
                    _local2 = "retry_fail";
                    break;
            };
            this.logTransactionData(_local2);
        }
        private function logErrorStats(_arg1:TransactionFaultEvent, _arg2:Boolean=false):void{
            var _local3:String = TransactionManager.lastFunc;
            var _local4:String = ("errorCode: " + _arg1.errorType.toString());
            var _local5:String = (_arg1.errorData) ? _arg1.errorData.toString() : "";
            var _local6:String = ("test_app_mode: " + Config.DEBUG_MODE.toString());
            var _local7:int = (_arg1.transaction) ? _arg1.transaction.getId() : null;
            StatsManager.count(StatsCounterType.ERRORS, (_arg2) ? StatsKingdomType.TRANSACTIONS_USERINIT : StatsKingdomType.TRANSACTIONS, _local3, _local4, _local6, _local5);
        }
        override protected function onStageMouseMove(_arg1:MouseEvent):void{
            StatsManager.notIdle();
            Global.appActive = true;
            UI.onStageMouseMove(_arg1);
        }
        override protected function onStageMouseClick(_arg1:MouseEvent):void{
            Global.lastInputTick = getTimer();
            Global.appActive = true;
            Global.world.resetIdleMissionTime();
            Global.world.resetGiftMissionTime();
            Global.world.resetGenericAdTime();
            if (((this.m_zmcFreeze) && ((this.m_zmcFreezeCount < 1)))){
                this.thawGame();
            };
        }
        override protected function onStageKeyDown(_arg1:KeyboardEvent):void{
            var isTestEnvironment:* = false;
            var targets:* = null;
            var target:* = null;
            var rollCallMechanic:* = null;
            var canPerformRollCall:* = false;
            var startedRollCall:* = false;
            var checkedIn1:* = false;
            var checkedIn2:* = false;
            var checkedIn3:* = false;
            var checkedIn4:* = false;
            var collected:* = false;
            var rollCall:* = null;
            var zooDialog:* = null;
            var xmlList:* = null;
            var node:* = null;
            var zoo:* = null;
            var banditsDialog:* = null;
            var captureFtueUrl:* = null;
            var captureFtueMessage:* = null;
            var captureFtueDialog:* = null;
            var zoosk:* = null;
            var mechmech:* = null;
            var zoose:* = null;
            var zoosg:* = null;
            var loader:* = null;
            var dictMech:* = null;
            var enclosure:* = null;
            var dmechanic:* = null;
            var gr:* = false;
            var mech:* = null;
            var e:* = _arg1;
            Global.lastInputTick = getTimer();
            Global.appActive = true;
            GlobalEngine.log("Keyboard", ((((((("Key down! keyCode: " + e.keyCode) + " ctrlKey: ") + e.ctrlKey) + " altKey: ") + e.altKey) + " shiftKey: ") + e.shiftKey));
            var fpsOverride:* = ((((((((DEBUG_PRODUCTION_OVERRIDE) && (e.ctrlKey))) && (e.altKey))) && (e.shiftKey))) && ((String.fromCharCode(e.charCode) == "p")));
            isTestEnvironment = RuntimeVariableManager.getBoolean("IS_TEST_ENVIRONMENT", false);
            if (!e.ctrlKey){
                return;
            };
            var char:* = String.fromCharCode(e.charCode);
            var handled:* = true;
            if (isTestEnvironment){
                switch (char){
                    case "l":
                        IdleDialogManager.toggleHotKeyForIdlePopUp();
                        break;
                    case "5":
                        GameTransactionManager.addTransaction(new TRefreshUser(GlobalEngine.socialNetwork.getLoggedInUser().name, false), true, true);
                        break;
                    default:
                        handled = false;
                };
            };
            if (((Config.DEBUG_MODE) || (fpsOverride))){
                GlobalEngine.log("Keyboard", ((((((((("Key down! char: " + String.fromCharCode(e.charCode)) + " keyCode: ") + e.keyCode) + " ctrlKey: ") + e.ctrlKey) + " altKey: ") + e.altKey) + " shiftKey: ") + e.shiftKey));
                if (!e.ctrlKey){
                    return;
                };
                switch (char){
                    case "1":
                        Global.world.printPerformanceData = true;
                        break;
                    case "`":
                        if (ConsoleStub.active == false){
                            loader = new PluginLoader("assets/plugin/console.swf");
                            loader.load(function (_arg1:Event):void{
                                if (((_arg1) && (_arg1.target.content))){
                                    ConsoleStub.install(_arg1.target.content);
                                    ConsoleHelper.activate();
                                };
                            });
                        };
                        break;
                    case "~":
                        Global.world.forceDefcon(GameWorld.DEFCON_LOWEST_LEVEL);
                        Global.world.printPerformanceData = true;
                        break;
                    case "/":
                        break;
                    case "4":
                        rollCallMechanic = (MechanicManager.getInstance().getMechanicInstance(Global.rollCallManager.getActiveObject("mun_townhall"), "rollCall", MechanicManager.ALL) as RollCallDataMechanic);
                        canPerformRollCall = rollCallMechanic.canPerformRollCall();
                        startedRollCall = rollCallMechanic.startRollCall();
                        checkedIn1 = rollCallMechanic.checkIn("-1");
                        checkedIn2 = rollCallMechanic.checkIn("-1");
                        rollCallMechanic.feedSent("-2");
                        checkedIn3 = rollCallMechanic.checkIn("-3");
                        checkedIn4 = rollCallMechanic.checkIn("234567");
                        collected = Global.rollCallManager.collect("12345678", Global.rollCallManager.getActiveObject("mun_townhall"));
                        break;
                    case "5":
                        GameTransactionManager.addTransaction(new TRefreshUser(GlobalEngine.socialNetwork.getLoggedInUser().name, false), true, true);
                        break;
                    case "1":
                        rollCall = new RollCallIntroDialog(Global.rollCallManager.getActiveObject("mun_townhall"), "", "RollCallIntroDialog", 0, null, "CityHallPatrol", "", true, 0, "", null, "START PAYROLL");
                        UI.displayPopup(rollCall);
                        break;
                    case "X":
                        targets = Global.world.getObjectsByNames(["bus_bakery", "bus_bakery_2"]);
                        if (targets.length){
                            UI.displayBusinessUpgradesDialog(targets[0], function ():Boolean{
                                return (false);
                            }, function ():void{
                            }, function ():void{
                            });
                        };
                        break;
                    case "Q":
                        if (Global.experimentManager.getVariant(ExperimentDefinitions.EXPERIMENT_BUSINESS_UPGRADES) == true){
                            GameTransactionManager.addTransaction(new TStartManualQuest("qm_upgrade_business"), true);
                        };
                        break;
                    case "q":
                        BanditManager.spawnStationHelicopter();
                        break;
                    case "x":
                        Global.guide.notify("CityHallUpgradeGuide");
                        break;
                    case "z":
                        targets = Global.world.getObjectsByNames(["bus_bakery", "bus_bakery_2"]);
                        if (targets.length){
                            dictMech = (MechanicManager.getInstance().getMechanicInstance(targets[0], "upgradeHelpers", MechanicManager.ALL) as IDictionaryDataMechanic);
                            if (dictMech){
                                dictMech.add("i31231922883", getTimer());
                                dictMech.add("i31443680054", getTimer());
                                dictMech.add("i31186873998", getTimer());
                            };
                        };
                        break;
                    case "Z":
                        GameTransactionManager.addTransaction(new TStartManualQuest("qm_xpromo_frontierville"), true);
                        break;
                    case "P":
                    case "p":
                        if (Global.ui.performanceTracker){
                            Global.ui.performanceTracker.visible = !(Global.ui.performanceTracker.visible);
                        };
                        break;
                    case "C":
                        IdleDialogManager.triggerIdleDialog();
                        break;
                    case "Y":
                    case "y":
                        Global.player.energy++;
                        break;
                    case "c":
                        CloudManager.toggleActivation();
                        break;
                    case "a":
                        RenderManager.dontRunScheduledAnimations = !(RenderManager.dontRunScheduledAnimations);
                        break;
                    case "j":
                        OffsetEditor.active = !(OffsetEditor.active);
                        break;
                    case "U":
                    case "u":
                        Global.ui.visible = !(Global.ui.visible);
                        break;
                    case "F":
                    case "f":
                        Utilities.toggleFullScreen();
                        break;
                    case "e":
                    case "E":
                        Global.world.citySim.toggleDebugRoadOverlay();
                        Global.world.citySim.waterManager.showDbgOverlay(!(Global.world.citySim.waterManager.showingDbgOverlay));
                        break;
                    case "i":
                        Global.hud.debugToggleDebugTextVisibility();
                        break;
                    case "n":
                        Global.world.citySim.npcManager.cheatToggleNpcVisibility();
                        break;
                    case "N":
                        zooDialog = new ZooDialog(null);
                        UI.displayPopup(zooDialog);
                        break;
                    case "m":
                        xmlList = Global.gameSettings.getItems();
                        node = xmlList[Math.floor((xmlList.length() * Math.random()))];
                        Global.ui.toaster.show(new ItemToaster("Hello There", "Awesomeness is in this things essence", Global.gameSettings.getImageByName(node.@name, "icon")));
                        break;
                    case "M":
                        SurveyManager.instance.displaySurveyOverlay(true);
                        break;
                    case "b":
                        Global.world.citySim.npcManager.cheatNpcRenderTest(true);
                        break;
                    case "g":
                        if (UI.isScreenFrozen()){
                            UI.thawScreen();
                        } else {
                            UI.freezeScreen();
                        };
                        break;
                    case "1":
                        zoo = new ZooDialog(null);
                        UI.displayPopup(zoo);
                        break;
                    case "2":
                        break;
                    case "3":
                        banditsDialog = new BanditCapturedDialog(6, null);
                        UI.displayPopup(banditsDialog);
                        break;
                    case "6":
                        captureFtueUrl = Global.gameSettings.getString("CNBcatchBanditFTUEAsset");
                        captureFtueMessage = ZLoc.t("Dialogs", "CapturedBandit_FTUE_message");
                        captureFtueDialog = new CharacterDialog(captureFtueMessage, "CapturedBandit", GenericDialogView.TYPE_OK, null, null, true, captureFtueUrl, "OkButton");
                        UI.displayPopup(captureFtueDialog);
                        break;
                    case "8":
                        this.debug_defcon++;
                        if (this.debug_defcon > GameWorld.DEFCON_HIGHEST_LEVEL){
                            this.debug_defcon = 0;
                        };
                        Global.world.forceDefcon(this.debug_defcon);
                        UI.displayMessage(("Defcon set to " + (this.debug_defcon + 1)));
                        break;
                    case "9":
                        Global.world.addGameMode(new GMDebugPathing(), false);
                        break;
                    case "0":
                        Road.showOverlay(!(Road.overlay));
                        break;
                    case "d":
                        Global.world.dooberManager.toogleEnableDoobers();
                        break;
                    case "B":
                        targets = Global.world.getObjectsByClass(Business);
                        if (targets.length){
                            target = targets[int((Math.random() * targets.length))];
                            BanditManager.addBanditWalker(new BanditData({id:6}), target);
                        };
                        break;
                    case "G":
                        GameTransactionManager.addTransaction(new TSaveOptions(Global.player.options));
                        break;
                    case "A":
                        zoosk = Global.world.getObjectsByClass(ZooEnclosure);
                        if (zoosk.length > 0){
                            enclosure = zoosk[0];
                            UI.displayPopup(new FriendRewardsDialog(zoosk[0], enclosure.getDataForMechanic("giftSenders")));
                        };
                        break;
                    case "t":
                    case "T":
                        Global.world.viralMgr.sendRollCallCollectReminder("31184494730", Global.rollCallManager.getActiveObject("mun_townhall"));
                        break;
                    case "r":
                        mechmech = (MechanicManager.getInstance().getMechanicInstance(Global.rollCallManager.getActiveObject("mun_townhall"), "rollCallTieredDooberValue", MechanicManager.ALL) as TieredDooberMechanic);
                        mechmech.executeOverrideForGameEvent(MechanicManager.ALL);
                        break;
                    case "8":
                        break;
                    case "9":
                        break;
                    case "0":
                        break;
                    case "d":
                        Global.world.dooberManager.toogleEnableDoobers();
                        break;
                    case "B":
                        targets = Global.world.getObjectsByClass(Business);
                        if (targets.length){
                            target = targets[int((Math.random() * targets.length))];
                            BanditManager.addBanditWalker(new BanditData({id:6}), target);
                        };
                        break;
                    case "G":
                        Global.world.showCollisionMap(true);
                        break;
                    case "A":
                        Global.gameSettings.testAllItemAssets();
                        break;
                    case "t":
                    case "T":
                        Global.world.viralMgr.sendZooFeed("enclosure_savannah", Global.player.cityName);
                        break;
                    case "#":
                        zoose = Global.world.getObjectsByClass(ZooEnclosure);
                        if (zoose.length > 0){
                            dmechanic = (MechanicManager.getInstance().getMechanicInstance(zoose[0], ZooManager.MECHANIC_STORAGE, MechanicManager.ALL) as IStorageMechanic);
                            if (dmechanic){
                                gr = dmechanic.purchase("animal_alligator", 1, ("zoo|adopted_animal|" + "animal_alligator"));
                            };
                        };
                        break;
                    case "$":
                        zoosg = Global.world.getObjectsByClass(ZooEnclosure);
                        if (zoosg.length > 0){
                            mech = (MechanicManager.getInstance().getMechanicInstance(zoosg[0], "giftSenders", MechanicManager.ALL) as IDictionaryDataMechanic);
                            if (mech){
                                mech.add("i31231922883", "animal_alligator");
                                mech.add("i31231922884", "welcomewagon");
                                mech.add("i31231922885", "animal_giraffe");
                            };
                        };
                        break;
                    default:
                        handled = false;
                };
            } else {
                switch (char){
                    case "f":
                    case "F":
                        Utilities.toggleFullScreen();
                        break;
                };
            };
            if (handled){
                e.stopImmediatePropagation();
                e.stopPropagation();
            };
        }
        override protected function onError(_arg1:ErrorEvent):void{
            if (Config.DEBUG_MODE){
                UI.displayMessage(_arg1.text, 0, null, "", true);
                if (((Global.ui) && ((Global.ui.parent == null)))){
                    addChild(Global.ui);
                    UI.pumpPopupQueue();
                };
            };
        }
        protected function onFocus():void{
            if (!((this.m_zmcFreeze) && (this.m_zmcOpen))){
                UI.thawScreen();
            };
        }
        protected function onZMCEvent(_arg1:Array):void{
            var reverseGift:* = false;
            var lootName:* = null;
            var lootAmount:* = 0;
            var reverseGift2:* = false;
            var strDialogMessage:* = null;
            var strTitleMessage:* = null;
            var typeDialog:* = 0;
            var params:* = _arg1;
            var action:* = "";
            if (((params) && ((params.length > 0)))){
                action = params[0];
            };
            var vDayVariant:* = Global.experimentManager.getVariant(ExperimentDefinitions.EXPERIMENT_VDAY_2011);
            GlobalEngine.info(action, params[1]);
            try {
                switch (action){
                    case "acceptInvite":
                        if ((((params.length > 1)) && (params[1]))){
                            this.acceptInvite(params[1]);
                        };
                        break;
                    case "acceptItem":
                        if ((((params.length > 2)) && (params[1]))){
                            reverseGift = (Number(params[2]) > 0);
                            this.acceptItem(params[1], reverseGift);
                        };
                        break;
                    case "acceptLoot":
                        if ((((((params.length >= 2)) && (params[1]))) && (params[2]))){
                            lootName = String(params[1]);
                            lootAmount = int(params[2]);
                            this.handleLoot(lootName, lootAmount);
                        };
                        break;
                    case "acceptTrain":
                        this.acceptTrain();
                        break;
                    case "acceptHolidayItem":
                        if ((((params.length > 2)) && (params[1]))){
                            reverseGift2 = (Number(params[2]) > 0);
                            this.acceptHolidayItem(params[1], reverseGift2);
                        };
                        break;
                    case "acceptValentineCard":
                        if (vDayVariant == 1){
                            if (((!(ValentineManager.m_shownIneligible)) && (!(ValentineManager.checkEligibility())))){
                                ValentineManager.m_shownIneligible = true;
                                strDialogMessage = ZLoc.t("Dialogs", "ValUI_StartupIneligible");
                                strTitleMessage = "ValUI";
                                typeDialog = GenericDialogView.TYPE_OK;
                                UI.displayMessage(strDialogMessage, typeDialog, null, strTitleMessage, true, "", strTitleMessage);
                            };
                        };
                        break;
                    case "ignoreValentineCard":
                        if (vDayVariant == 1){
                            ValentineManager.removeValentineCard(params[1], params[2]);
                            Global.hud.updateVdayCount();
                        };
                        break;
                    case "acceptWorker":
                        if (params[1]){
                            Global.player.commodities.add("goods", params[1]);
                            Global.hud.updateCommodities();
                        };
                        break;
                    case "addDonuts":
                        if (params[1]){
                            BanditManager.addDonutToCop(("i" + params[1]));
                        } else {
                            BanditManager.addDonutToCop();
                        };
                        break;
                    case "addNoodles":
                        Global.peddlerManager.addDonutsFromZMC();
                        break;
                    case "addEnergy":
                        Global.player.energy++;
                        break;
                };
            } catch(pError:Error) {
                ErrorManager.addError(((((("Error receiving ZMC call from JS:\n" + pError.message) + "\n") + pError.getStackTrace()) + "\n") + pError.toString()));
            };
        }
        protected function acceptInvite(_arg1:Object):void{
            var _local3:String;
            var _local2:Array = Global.player.neighbors;
            for each (_local3 in _local2) {
                if (_local3 == _arg1.uid){
                    return;
                };
            };
            _local2.push(_arg1.uid);
            Global.player.neighbors = _local2;
            UI.addToFriendBarData(_arg1);
            if (Global.ui){
                Global.ui.m_friendBar.updateNeighbors(Global.friendbar);
            };
            if (UI.m_catalog){
                UI.m_catalog.updateChangedCells();
            };
            Global.world.citySim.trainManager.onNeighborAdded();
        }
        protected function acceptItem(_arg1:String, _arg2:Boolean):void{
            if (!_arg2){
                Global.player.inventory.addItems(_arg1, 1);
            };
        }
        protected function handleLoot(_arg1:String, _arg2:int):void{
            GlobalEngine.info("handleLoot", ((_arg1 + " ") + _arg2));
            switch (_arg1){
                case "coins":
                    Global.player.gold = (Global.player.gold + _arg2);
                    break;
                case "xp":
                    Global.player.xp = (Global.player.xp + _arg2);
                    break;
                case "energy":
                    Global.player.energy = (Global.player.energy + _arg2);
                    break;
                case "goods":
                    Global.player.commodities.add(_arg1, _arg2);
                    break;
                default:
                    if (Global.gameSettings.getCollectionByCollectableName(_arg1) != null){
                        Global.player.addCollectable(_arg1);
                    } else {
                        Global.player.inventory.addItems(_arg1, _arg2);
                    };
            };
        }
        protected function acceptHolidayItem(_arg1:String, _arg2:Boolean):void{
            if (!_arg2){
                Global.player.inventory.addItems(_arg1, 1);
                if (HolidayTree.instance != null){
                    HolidayTree.instance.reloadImage();
                    HolidayTree.doPreHolidayStartupChecks(false);
                };
            };
        }
        protected function acceptTrain():void{
            Global.player.gold = (Global.player.gold + Global.gameSettings.getInt("trainOrderRequestCoinReward", 10));
        }
        private function onEnterFrame(_arg1:Event):void{
            GlobalEngine.zaspManager.preUpdate();
            InputManager.checkMouseMove();
            if (Global.world){
                Global.world.updateWorld();
            };
            if (this.m_zmcFreezeCount > 0){
                this.m_zmcFreezeCount--;
            };
            BackgroundInitialization.process();
            GlobalEngine.zaspManager.postUpdate();
        }
        private function onMouseLeaveFrame(_arg1:Event):void{
            Global.appActive = false;
        }
        override public function disableAllInput():void{
            super.disableAllInput();
            UI.freezeScreen();
        }
        override public function enableAllInput():void{
            super.enableAllInput();
            UI.thawScreen();
        }
        public function setZBarQueue(_arg1:Boolean):void{
            ZBarNotifier.queueNotifications = _arg1;
        }
        public function logShowFeedDialog():void{
            this.m_feedOpenTime = getTimer();
            StatsManager.count("farm_world_action", "Feed_Open");
        }
        public function permissionDialogClosed(_arg1:Boolean):void{
            GlobalEngine.socialNetwork.onPermissionDialogClosed(_arg1);
        }
        public function logCloseFeedDialog(_arg1:Object=null):void{
            var _local4:String;
            var _local5:String;
            ViralManager.doUIThaw();
            var _local2:Number = getTimer();
            var _local3:int = (_local2 - this.m_feedOpenTime);
            _local3 = int((_local3 / 10000));
            if (_local3 > 6){
                _local4 = ">1 minute";
            } else {
                _local4 = (Number((_local3 + 1)).toString() + "0 seconds");
            };
            if (((!((_arg1 == null))) && ((_arg1 is String)))){
                _local5 = (_arg1 as String);
                switch (_local5){
                    case "posted":
                        StatsManager.count("farm_world_action", "Feed_Published", _local4);
                        break;
                    case "closed":
                        StatsManager.count("farm_world_action", "Feed_Closed", _local4);
                        break;
                    case "skipped":
                        StatsManager.count("farm_world_action", "Feed_Skipped", _local4);
                        break;
                    default:
                        StatsManager.count("farm_world_action", "Feed_Unknown", _local4);
                };
            } else {
                StatsManager.count("farm_world_action", "Feed_Close", _local4);
            };
            GlobalEngine.socialNetwork.onFeedClosed();
        }
        public function freezeGame(_arg1:Object=null):void{
            UI.freezeScreen(false, true);
        }
        public function ZMCFreezeGame(_arg1:Object=null):void{
            if (!this.m_zmcOpen){
                return;
            };
            var _local2:int = Global.experimentManager.getVariant(ExperimentDefinitions.EXPERIMENT_ZMC_FREEZE_GAME);
            if (_local2 != ExperimentDefinitions.ZMC_FREEZE){
                return;
            };
            this.m_zmcFreeze = true;
            this.m_zmcFreezeCount = (this.FRAME_RATE * 5);
            UI.freezeScreen(false, true);
        }
        public function thawGame(_arg1:Object=null):void{
            this.m_zmcFreeze = false;
            this.m_zmcFreezeCount = 0;
            UI.thawScreen();
        }
        public function onDynamicTrayClosed():void{
            this.thawGame();
            FrameManager.onDynamicTrayClosed();
        }
        public function onZMCOpen():void{
            this.m_zmcOpen = true;
            StatsManager.count(StatsKingdomType.ZMC_EVENT, "open");
        }
        public function onZMCClose():void{
            this.m_zmcOpen = false;
            StatsManager.count(StatsKingdomType.ZMC_EVENT, "close");
            this.thawGame();
        }
        public function onZMCLoad():void{
            if (Global.zmcOpenedOnInit){
                Global.zmcOpenedOnInit = false;
                StartupSessionTracker.interactive();
            };
        }

    }
}//package 

import Engine.Transactions.*;

class TransactionTrackingData {

    public static const MAX_TRACKED:int = 40;

    public var transaction:Transaction;
    public var addTime:Number = -1;
    public var dispatchTime:Number = -1;
    public var responseTime:Number = -1;
    public var serverDuration:Number = -1;

    public function TransactionTrackingData(_arg1:Transaction):void{
        this.transaction = _arg1;
        this.addTime = GlobalEngine.currentTime;
    }
    public function get isComplete():Boolean{
        return (((!((this.dispatchTime == -1))) && (!((this.responseTime == -1)))));
    }
    public function get isDispatched():Boolean{
        return (!((this.dispatchTime == -1)));
    }
    public function get transactionTime():Number{
        return ((this.responseTime - this.dispatchTime));
    }

}
class BatchTrackingData {

    public static const MAX_TRACKED:int = 15;

    public var dispatchTime:Number = -1;
    public var responseTime:Number = -1;
    public var numTransactions:int = 0;
    public var batchServerTimeElapsed:Number = -1;

    public function BatchTrackingData(){
    }
    public function get isComplete():Boolean{
        return (((!((this.dispatchTime == -1))) && (!((this.responseTime == -1)))));
    }
    public function get batchTimeElapsed():Number{
        return ((this.responseTime - this.dispatchTime));
    }

}
